<template>
  <Dialog v-model="dialogVisible" title="数据权限">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="80px">
      <el-form-item label="角色名称">
        <el-tag>{{ formData.name }}</el-tag>
      </el-form-item>
      <el-form-item label="角色编码">
        <el-tag>{{ formData.code }}</el-tag>
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="formData.dataScope">
          <el-option
            v-for="dict in system_perm_data_scope"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="数据权限"
        v-show="formData.dataScope === SystemDataScopeEnum.Dept_Custom"
      >
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptCheckAll" @change="handleCheckedTreeCheckAll"
          >全选/全不选</el-checkbox
        >
        <el-checkbox v-model="deptCheckLinked">父子联动</el-checkbox>
        <el-tree
          ref="deptTreeRef"
          class="tree-border"
          :data="deptTree"
          :props="defaultProps"
          empty-text="加载中，请稍候"
          node-key="id"
          show-checkbox
          :check-strictly="!deptCheckLinked"
          :default-expand-all="deptExpand"
        />
        注意：不包括半选状态的部门
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { defaultProps, handleTree } from '@/utils/tree'
import * as RoleApi from '@/api/system/role'
import * as DeptApi from '@/api/system/dept'
import * as PermissionApi from '@/api/system/permission'
import { EnableStatusEnum, SystemDataScopeEnum } from '@/utils/constants'

defineOptions({ name: 'SystemRoleDataPermissionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const { system_perm_data_scope } = useIntDict(DICT_TYPE.system_perm_data_scope)

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined as any,
  name: '',
  code: '',
  dataScope: undefined as any,
  dataScopeDeptIds: [] as number[]
})
const formRef = ref() // 表单 Ref

const deptList = ref() // 部门列表数据
const deptTree = ref() // 部门树数据
const deptExpand = ref(true) // 是否展开
const deptCheckAll = ref(false) // 全选/全不选
const deptCheckLinked = ref(false) // 是否父子联动
const deptTreeRef = ref() // 部门树组件

const open = async (id: number) => {
  dialogVisible.value = true
  resetForm()
  formLoading.value = true
  try {
    formData.value = await RoleApi.getRole(id)
    deptList.value = await DeptApi.getDeptSimpleList(EnableStatusEnum.Enabled)
    deptTree.value = handleTree(deptList.value)
    nextTick(() => {
      // dom渲染完后再设置树节点状态
      formData.value.dataScopeDeptIds?.forEach((deptId) => {
        // (key/data, checked, deep)
        deptTreeRef.value.setChecked(deptId, true, false)
      })
    })
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  let err = await formValidate(formRef)
  if (err) return
  formLoading.value = true
  try {
    const data = {
      roleId: formData.value.id,
      dataScope: formData.value.dataScope,
      dataScopeDeptIds:
        formData.value.dataScope !== SystemDataScopeEnum.Dept_Custom
          ? []
          : deptTreeRef.value?.getCheckedKeys(false) // 不包括半选状态的节点，包含则有风险
    }
    await PermissionApi.assignRoleDataScope(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  deptExpand.value = true
  deptCheckAll.value = false
  deptCheckLinked.value = false
  formData.value = {
    id: undefined,
    name: '',
    code: '',
    dataScope: undefined,
    dataScopeDeptIds: []
  }
  deptTreeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}

const handleCheckedTreeExpand = () => {
  const nodes = deptTreeRef.value?.store.nodesMap
  for (const nodeKey in nodes) {
    if (nodes[nodeKey].expanded !== deptExpand.value) {
      nodes[nodeKey].expanded = deptExpand.value
    }
  }
}

const handleCheckedTreeCheckAll = () => {
  deptTreeRef.value?.setCheckedNodes(deptCheckAll.value ? deptList.value : [])
}
</script>

<style scoped lang="scss"></style>
